package com.youku.bootstrap;

import static org.junit.Assert.assertNotNull;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;

import com.youku.component.Project;
import com.youku.util.CronExpressionHelper;

/**
 * 定期执行器
 * @author loda
 *
 */
public class RegularExecutor extends BaseExecutor{

	@Override
	public void execute() {
		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			scheduler.start();
			for (Project p : projects) {
				assertNotNull("项目不能为空", p);

				JobDetail job = newJob(PlatformExecuteJob.class).withIdentity("job:pid_" + p.getId()).build();

				job.getJobDataMap().put("project", p);

				Trigger trigger = newTrigger().withIdentity("trigger:pid_" + p.getId())
						.withSchedule(cronSchedule(CronExpressionHelper.build(p.getCronExpression()))).build();
				scheduler.scheduleJob(job, trigger);

			}

			Thread.sleep(300L * 1000L);

			scheduler.shutdown();

		} catch (RuntimeException e) {
			System.out.println(e.getMessage());
		} catch (SchedulerException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}
